<!--
 * Copyright © 2022 XXXXXXXXX
 * @Author: zhangxiang
 * @Date: 2022-08-26 15:53:26
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-09-26 11:39:17
 * @Description:
 *
-->

<template>
  <el-dialog
    class="scale-strategy-dialog"
    :title="title"
    :visible="show"
    width="700px"
    top="10vh"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="closeClick"
  >
    <div class="serviceName">
      微服务名称：{{ serviceName
      }}<span class="text">，请选择需要配置的弹性扩缩策略</span>
    </div>
    <el-tabs
      v-model="scaleType"
      type="card"
      class="tabs"
      @tab-click="handleTabClick"
    >
      <el-tab-pane
        v-for="item in Object.keys(scaleTypes)"
        :key="item"
        :disabled="item === 'vm' && isEdit && !canEditScalevm"
        :label="scaleTypes[item].label"
        :name="item"
      />
    </el-tabs>
    <!-- 跨集群扩缩容 -->
    <template v-if="scaleType === 'cluster'">
      <el-radio-group v-model="policyCluster" class="radios">
        <el-radio label="none">不配置</el-radio>
        <el-radio
          label="cluster"
          :disabled="info.category === 'BIGDATA'"
        >配置<el-tooltip
          v-if="info.category === 'BIGDATA'"
          effect="dark"
          content="大数据场景下的微服务目前暂不支持跨云业务调度"
          placement="top"
        >
          <i
            class="el-icon-info icon"
            style="font-size: 14px; margin-left: 10px"
          ></i> </el-tooltip></el-radio>
      </el-radio-group>
      <el-collapse
        v-if="policyCluster === 'cluster'"
        v-model="collapseActive"
        accordion
        class="collapse"
      >
        <el-collapse-item title="详细参数" name="cluster">
          <!-- 表单配置 -->
          <el-form
            ref="policyClusterForm"
            key="policyClusterForm"
            class="scale-form"
            :rules="policyClusterRules"
            :model="policyClusterForm"
            label-width="100px"
            size="medium"
          >
            <el-form-item label="扩缩容策略" prop="metric">
              <el-select
                v-model="policyClusterForm.metric"
                placeholder="请选择扩缩容策略"
                style="width: 60%"
              >
                <el-option
                  v-for="item in metricOptionsCluster"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="配置参数" prop="clusterScaleThreshold">
              <el-row type="flex" align="middle">
                <span class="subtitle cluster">跨集群扩容阈值</span>
                <el-slider
                  v-model="policyClusterForm.clusterScaleUp"
                  class="slider"
                  :format-tooltip="percentageValueFormat"
                  :max="100"
                  show-input
                />
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="判断微服务扩容指标利用率较高且部署该微服务的所有集群的伸缩组达到跨集群扩容阈值"
                  placement="top"
                >
                  <i
                    class="el-icon-info icon"
                    style="font-size: 18px; margin-left: 10px"
                  ></i>
                </el-tooltip>
              </el-row>
              <el-row type="flex" align="middle">
                <span class="subtitle cluster">跨集群缩容阈值</span>
                <el-slider
                  v-model="policyClusterForm.clusterScaleDown"
                  class="slider"
                  :format-tooltip="percentageValueFormat"
                  :max="100"
                  show-input
                />
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="判断当前集群是否达到集群缩容阈值（微服务所有pod的资源使用量/分配pod资源总量）且副本数到了最小值"
                  placement="top"
                >
                  <i
                    class="el-icon-info icon"
                    style="font-size: 18px; margin-left: 10px"
                  ></i>
                </el-tooltip>
              </el-row>
            </el-form-item>
            <!-- 冷却时间 -->
            <el-form-item label="触发条件" prop="cooldownDelay">
              <el-row type="flex" align="middle">
                <span class="subtitle">冷却时间</span>
                <el-input-number
                  v-model="policyClusterForm.cooldownDelay"
                  class="cooldownDelay"
                  :min="0"
                  :precision="0"
                  label="冷却时间"
                />
                <span style="margin-left: 10px">mins</span>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="完成集群扩缩操作之后，在冷却时间内会拒绝再次进行扩缩操作"
                  placement="top"
                >
                  <i
                    class="el-icon-info icon"
                    style="font-size: 18px; margin-left: 10px"
                  ></i>
                </el-tooltip>
              </el-row>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </template>
    <template v-if="scaleType === 'container'">
      <el-radio-group
        v-model="policyCtn"
        class="radios"
        @input="policyCtnChange"
      >
        <el-radio label="none">不配置</el-radio>
        <el-radio label="history">基于历史数据建模分析的容器扩缩容</el-radio>
        <el-radio label="hpa">基于自定义HPA的容器扩缩容</el-radio>
      </el-radio-group>
      <el-collapse
        v-if="policyCtn === 'hpa'"
        v-model="collapseActive"
        accordion
        class="collapse"
      >
        <el-collapse-item title="详细参数" name="hpa">
          <!-- 基于自定义HPA的容器扩缩容 -->
          <el-form
            ref="policyCtnHpaForm"
            key="policyCtnHpaForm"
            class="scale-form"
            :rules="policyCtnHpaRules"
            :model="policyCtnHpaForm"
            label-width="100px"
            size="medium"
          >
            <el-form-item label="扩缩容策略" prop="metric">
              <el-select
                v-model="policyCtnHpaForm.metric"
                placeholder="请选择扩缩容策略"
                style="width: 60%"
              >
                <el-option
                  v-for="item in metricOptionsHPA"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <!-- 最小实例数 -->
            <el-form-item label="配置参数" prop="minReplicas">
              <el-row type="flex" align="middle">
                <span class="subtitle">最小实例数</span>
                <el-slider
                  v-model="policyCtnHpaForm.minReplicas"
                  class="slider"
                  :max="20"
                  :min="1"
                  :precision="0"
                  show-input
                />
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="请选择1-20之间的实例数"
                  placement="top"
                >
                  <i
                    class="el-icon-info icon"
                    style="font-size: 18px; margin-left: 10px"
                  ></i>
                </el-tooltip>
              </el-row>
            </el-form-item>
            <!-- 最大实例数 -->
            <el-form-item label="" prop="maxReplicas">
              <el-row type="flex" align="middle">
                <span class="subtitle">最大实例数</span>
                <el-slider
                  v-model="policyCtnHpaForm.maxReplicas"
                  class="slider"
                  :max="20"
                  :min="1"
                  :precision="0"
                  show-input
                />
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="请选择1-20之间的实例数"
                  placement="top"
                >
                  <i
                    class="el-icon-info icon"
                    style="font-size: 18px; margin-left: 10px"
                  ></i>
                </el-tooltip>
              </el-row>
            </el-form-item>
            <!-- 期望值 -->
            <el-form-item label="" prop="expectedValue">
              <el-row type="flex" align="middle">
                <span class="subtitle">期望值</span>
                <el-slider
                  v-model="policyCtnHpaForm.expectedValue"
                  class="slider"
                  :max="100"
                  :precision="0"
                  :format-tooltip="percentageValueFormat"
                  show-input
                />
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="期望资源的平均利用率，用于计算需要伸缩的实例数"
                  placement="top"
                >
                  <i
                    class="el-icon-info icon"
                    style="font-size: 18px; margin-left: 10px"
                  ></i>
                </el-tooltip>
              </el-row>
            </el-form-item>
            <!-- 冷却时间 -->
            <el-form-item label="触发条件" prop="cooldownDelay">
              <el-row type="flex" align="middle">
                <span class="subtitle">冷却时间</span>
                <el-input-number
                  v-model="policyCtnHpaForm.cooldownDelay"
                  class="cooldownDelay"
                  :min="0"
                  :precision="0"
                  label="冷却时间"
                />
                <span style="margin-left: 10px">mins</span>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="只有满足连续超过等待窗口的期望副本数小于当前副本数，启动缩容"
                  placement="top"
                >
                  <i
                    class="el-icon-info icon"
                    style="font-size: 18px; margin-left: 10px"
                  ></i>
                </el-tooltip>
              </el-row>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </template>
    <template v-if="scaleType === 'vm'">
      <el-radio-group v-model="policyVM" class="radios" @input="policyVMChange">
        <el-radio label="none">不配置</el-radio>
        <el-radio
          label="vm"
          :disabled="policyCtn === 'none'"
        >配置<el-tooltip
          effect="dark"
          content="需要先配置容器扩缩容，才能启动虚机扩缩容配置"
          placement="right"
        >
          <i
            class="el-icon-info icon"
            style="font-size: 14px; margin-left: 10px"
          ></i> </el-tooltip></el-radio>
      </el-radio-group>
      <el-collapse
        v-if="policyVM === 'vm'"
        v-model="collapseActive"
        class="collapse"
        accordion
      >
        <el-collapse-item title="详细参数" name="vm">
          <ScaleStrategyVM
            ref="scaleStrategyVM"
            :scene="isEdit ? 2 : 1"
            :policy-param.sync="policyVMParam"
          />
        </el-collapse-item>
      </el-collapse>
    </template>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="cancelClick">取 消</el-button>
      <el-button
        type="primary"
        size="small"
        :loading="confirmLoading"
        @click="confirmClick"
      >确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  STRATEGY_SCALE_TYPE,
  STRATEGY_SCALE_NAME_ALL,
  STRATEGY_SCALE_VM_MAX_DEFAULT,
  STRATEGY_SCALE_VM_MIN_DEFAULT,
  STRATEGY_SCALE_HPA,
  STRATEGY_SCALE_CLUSTER
} from '@/utils/cnap/constant'
import ScaleStrategyVM from './ScaleStrategyVM.vue'
import { addScaleStrategy } from '@/api/cnap/app-service'

export default {
  name: 'ScaleStrategyDialog',
  components: { ScaleStrategyVM },
  props: {
    // 显示
    show: {
      type: Boolean,
      default: false
    },
    // 编辑
    isEdit: {
      type: Boolean,
      default: false
    },
    // 虚机扩缩容是否可编辑
    canEditScalevm: {
      type: Boolean,
      default: true
    },
    // 数据
    info: {
      type: Object,
      default: () => {}
    },
    // 已选择的云商集群
    choosedClusters: {
      type: Array,
      default: () => []
    }
  },
  data() {
    /**
     * @description: 检测最小实例数合法性
     * @param {*} rule
     * @param {*} value
     * @param {*} callback
     * @return {*}
     */
    var validateMinReplicas = (rule, value, callback) => {
      if (
        Number.isInteger(this.policyCtnHpaForm.minReplicas) &&
        this.policyCtnHpaForm.minReplicas >= 1 &&
        this.policyCtnHpaForm.minReplicas <= 20
      ) {
        callback()
      } else {
        callback(new Error('请输入1-20之间的整数'))
      }
    }
    /**
     * @description: 检测最大实例数合法性
     * @param {*} rule
     * @param {*} value
     * @param {*} callback
     * @return {*}
     */
    var validateMaxReplicas = (rule, value, callback) => {
      if (
        Number.isInteger(this.policyCtnHpaForm.maxReplicas) &&
        this.policyCtnHpaForm.maxReplicas >= 1 &&
        this.policyCtnHpaForm.maxReplicas <= 20
      ) {
        if (
          this.policyCtnHpaForm.maxReplicas < this.policyCtnHpaForm.minReplicas
        ) {
          callback(new Error('最大实例数需要大于等于最小实例数'))
        } else {
          callback()
        }
      } else {
        callback(new Error('请输入1-20之间的整数'))
      }
    }
    /**
     * @description: 检测跨集群扩缩容阈值合法性
     * @param {*} rule
     * @param {*} value
     * @param {*} callback
     * @return {*}
     */
    var validateClusterScaleThreshold = (rule, value, callback) => {
      if (
        Number.isInteger(this.policyClusterForm.clusterScaleUp) &&
        this.policyClusterForm.clusterScaleUp >= 1 &&
        this.policyClusterForm.clusterScaleUp <= 100
      ) {
        if (
          Number.isInteger(this.policyClusterForm.clusterScaleDown) &&
          this.policyClusterForm.clusterScaleDown >= 0 &&
          this.policyClusterForm.clusterScaleDown <= 100
        ) {
          if (
            this.policyClusterForm.clusterScaleUp <=
            this.policyClusterForm.clusterScaleDown
          ) {
            callback(new Error('跨集群扩容阈值需要大于跨集群缩容阈值'))
          } else {
            callback()
          }
        } else {
          callback(new Error('跨集群缩容阈值只能为0-100之间的整数'))
        }
      } else {
        callback(new Error('跨集群扩容阈值只能为1-100之间的整数'))
      }
    }
    return {
      title: '添加弹性扩缩策略', // 标题
      serviceName: '',
      collapseActive: '',
      scaleType: 'vm',
      scaleTypes: STRATEGY_SCALE_TYPE, // 扩缩容类型
      policyVM: 'none',
      policyVMParam: [],
      policyVMParamInit: [], // 初始的配置参数
      vmParamChanged: false,
      policyCtn: 'none',
      policyCtnHpaForm: {
        metric: 'cpu', // 自定义扩缩容策略标准
        minReplicas: 1, // 最小实例数
        maxReplicas: 8, // 最大实例数
        expectedValue: 50, // 期望值
        cooldownDelay: 5 // 冷却时间
      },
      policyCtnHpaRules: {
        // 扩缩容策略
        metric: [
          { required: true, message: '请选择扩缩容策略', trigger: 'change' }
        ],
        minReplicas: [{ required: true, validator: validateMinReplicas }], // 最小实例
        maxReplicas: [{ required: true, validator: validateMaxReplicas }], // 最大实例
        expectedValue: [{ pattern: /^([0-9]*)$/, message: '请输入整数' }], // 期望值
        // 冷却时间
        cooldownDelay: [
          { required: true, message: '请选择触发条件', trigger: 'blur' }
        ]
      },
      policyCluster: 'none',
      policyClusterForm: {
        metric: 'cpu', // 扩缩容策略标准
        clusterScaleUp: 80, // 跨集群扩容阈值
        clusterScaleDown: 20, // 跨集群缩容阈值
        cooldownDelay: 5 // 冷却时间
      },
      policyClusterRules: {
        // 扩缩容策略
        metric: [
          { required: true, message: '请选择扩缩容策略', trigger: 'change' }
        ],
        clusterScaleThreshold: [
          {
            required: true,
            validator: validateClusterScaleThreshold,
            trigger: 'change'
          }
        ], // 跨集群扩缩容阈值 配置
        // 冷却时间
        cooldownDelay: [
          { required: true, message: '请选择触发条件', trigger: 'blur' }
        ]
      },
      confirmLoading: false
    }
  },
  computed: {
    /**
     * @description: 跨集群的扩缩容策略
     * @return {*}
     */
    metricOptionsCluster() {
      const options = []
      // 转成数组
      Object.keys(STRATEGY_SCALE_CLUSTER).forEach((element) => {
        options.push({
          value: element,
          label: STRATEGY_SCALE_CLUSTER[element].name
        })
      })
      return options
    },
    /**
     * @description: HPA的扩缩容策略
     * @return {*}
     */
    metricOptionsHPA() {
      const options = []
      // 转成数组
      Object.keys(STRATEGY_SCALE_HPA).forEach((element) => {
        options.push({
          value: element,
          label: STRATEGY_SCALE_HPA[element].name
        })
      })
      return options
    }
  },
  watch: {
    /**
     * @description: 监听是否是编辑模式
     * @return {*}
     */
    isEdit: {
      handler(newVal) {
        if (newVal) {
          // 初始化数据
          this.title = '编辑弹性扩缩策略'
          this.serviceName = this.info.serviceName
          if (!this.info.canEditScalevm) {
            // 虚机扩缩容不可编辑
            // 此时默认显示 容器扩缩容
            this.scaleType = 'container'
          }
          // 跨集群扩缩容
          const scaleCluster = Array.isArray(this.info.scaleStrategy)
            ? this.info.scaleStrategy.filter((element) => {
              return element.scaleType === 'cluster'
            })
            : []
          if (scaleCluster.length > 0) {
            try {
              const strategyParam = JSON.parse(scaleCluster[0].strategyParam) // JSON解析
              this.policyCluster = ['none', 'cluster'].includes(
                strategyParam.policy
              )
                ? strategyParam.policy
                : 'none'
              if (strategyParam.policy === 'cluster') {
                // 预置数据
                this.policyClusterForm.metric = strategyParam.metric
                this.policyClusterForm.clusterScaleUp =
                  strategyParam.clusterScaleUp
                this.policyClusterForm.clusterScaleDown =
                  strategyParam.clusterScaleDown
                this.policyClusterForm.cooldownDelay =
                  strategyParam.cooldownDelay
              }
            } catch (err) {
              console.log(err)
            }
          }
          // 容器扩缩容
          const scaleContainer = Array.isArray(this.info.scaleStrategy)
            ? this.info.scaleStrategy.filter((element) => {
              return element.scaleType === 'container'
            })
            : []
          if (scaleContainer.length > 0) {
            try {
              const strategyParam = JSON.parse(scaleContainer[0].strategyParam) // JSON解析
              this.policyCtn = ['none', 'hpa', 'history'].includes(
                strategyParam.policy
              )
                ? strategyParam.policy
                : 'none'
              if (strategyParam.policy === 'hpa') {
                // 预置数据
                this.policyCtnHpaForm.metric = strategyParam.metric
                this.policyCtnHpaForm.minReplicas = strategyParam.minReplicas
                this.policyCtnHpaForm.maxReplicas = strategyParam.maxReplicas
                this.policyCtnHpaForm.expectedValue =
                  strategyParam.expectedValue
                this.policyCtnHpaForm.cooldownDelay =
                  strategyParam.cooldownDelay
              }
            } catch (err) {
              console.log(err)
            }
          }
          // 虚机扩缩容
          const scaleVM = Array.isArray(this.info.scaleStrategy)
            ? this.info.scaleStrategy.filter((element) => {
              return element.scaleType === 'vm'
            })
            : []
          if (scaleVM.length > 0) {
            try {
              const strategyParam = JSON.parse(scaleVM[0].strategyParam) // JSON解析
              this.policyVM = ['none', 'vm'].includes(strategyParam.policy)
                ? strategyParam.policy
                : 'none'
              if (strategyParam.policy === 'vm') {
                // 预置数据
                this.policyVMParam = strategyParam.param
                this.policyVMParamInit = JSON.parse(
                  JSON.stringify(this.policyVMParam)
                )
              }
            } catch (err) {
              console.log(err)
            }
          }
        } else {
          // 预置数据
          this.serviceName = this.info.serviceNames.join(',')
          this.policyVMParam = []
          this.policyVMParamInit = JSON.parse(
            JSON.stringify(this.policyVMParam)
          )
        }
      },
      immediate: true
    },
    /**
     * @description: 监听虚机策略参数变化
     * @return {*}
     */
    policyVMParam: {
      handler(newVal) {
        // 处理后的参数
        const oldParamSorted = []
        this.policyVMParamInit.forEach((element) => {
          const newElement = {}
          // key值排序
          Object.keys(element)
            .sort()
            .forEach((key) => {
              newElement[key] = String(element[key])
            })
          oldParamSorted.push(newElement)
        })
        // 处理后的参数
        const newParamSorted = []
        this.policyVMParam.forEach((element) => {
          const newElement = {}
          // key值排序
          Object.keys(element)
            .sort()
            .forEach((key) => {
              newElement[key] = String(element[key])
            })
          newParamSorted.push(newElement)
        })
        // 使用json字符串进行比较
        this.vmParamChanged =
          JSON.stringify(oldParamSorted) !== JSON.stringify(newParamSorted)
        // console.log(JSON.stringify(oldParamSorted), JSON.stringify(newParamSorted))
        // console.log(this.vmParamChanged)
      },
      deep: true
    }
  },
  methods: {
    /**
     * @description: 虚机扩缩容
     * @param {*} val
     * @return {*}
     */
    policyVMChange(val) {
      if (val === 'vm') {
        if (this.policyVMParam.length === 0) {
          this.policyVMParam = [
            STRATEGY_SCALE_VM_MAX_DEFAULT,
            STRATEGY_SCALE_VM_MIN_DEFAULT
          ]
        }
      }
    },
    /**
     * @description: 容器扩缩容切换
     * @param {*} val
     * @return {*}
     */
    policyCtnChange(val) {
      if (val === 'none') {
        this.policyVM = 'none'
        this.policyVMParam = []
      }
    },
    /**
     * @description: 期望值格式化
     * @param {*} val
     * @return {*}
     */
    percentageValueFormat(val) {
      return val + '%'
    },
    /**
     * @description: tab点击
     * @return {*}
     */
    handleTabClick() {
      this.collapseActive = ''
    },
    /**
     * @description: 校验参数
     * @return {*}
     */
    validateVMParam() {
      const reg = /^((?!0)\d{1,2})$/
      const maxIndex = this.policyVMParam.findIndex((item) => {
        return item.type === 'max'
      })
      const minIndex = this.policyVMParam.findIndex((item) => {
        return item.type === 'min'
      })
      if (maxIndex >= 0 && !reg.test(this.policyVMParam[maxIndex].value)) {
        return '扩容策略触发条件数值只能为0~100之间的整数'
      }
      if (minIndex >= 0 && !reg.test(this.policyVMParam[minIndex].value)) {
        return '缩容策略触发条件数值只能为0~100之间的整数'
      }
      if (maxIndex >= 0 && minIndex >= 0) {
        if (
          this.policyVMParam[maxIndex].resource !==
          this.policyVMParam[minIndex].resource
        ) {
          return '扩容策略和缩容策略的触发条件需要一致'
        } else if (
          Number(this.policyVMParam[maxIndex].value) <=
          Number(this.policyVMParam[minIndex].value)
        ) {
          return '扩容策略最大值的下限要大于缩容策略最小值的上限'
        }
      }
      return ''
    },
    /**
     * @description: 确定
     * @return {*}
     */
    confirmClick() {
      // 虚机扩缩容数据校验
      if (this.validateVMParam()) {
        this.$message.warning('虚机扩缩容策略参数配置有误，请检查')
        this.scaleType = 'vm'
        this.collapseActive = 'vm'
        if (
          this.scaleType === 'vm' &&
          this.policyVM === 'vm' &&
          this.$refs.scaleStrategyVM
        ) {
          this.$refs.scaleStrategyVM.validateForm()
        }
        return
      }
      // HPA容器扩缩容数据校验
      if (
        this.policyCtn === 'hpa' &&
        this.policyCtnHpaForm.maxReplicas < this.policyCtnHpaForm.minReplicas
      ) {
        this.$message.warning('容器扩缩容策略参数配置有误，请检查')
        this.scaleType = 'container'
        this.collapseActive = 'hpa'
        return
      }
      // 跨集群扩缩容数据校验
      if (
        this.policyCluster === 'cluster' &&
        this.policyClusterForm.clusterScaleUp <=
          this.policyClusterForm.clusterScaleDown
      ) {
        this.$message.warning('跨集群扩缩容策略参数配置有误，请检查')
        this.scaleType = 'cluster'
        this.collapseActive = 'cluster'
        return
      }

      // 虚机策略参数有改变
      if (
        this.policyVM === 'vm' &&
        this.choosedClusters.length > 0 &&
        this.vmParamChanged
      ) {
        const h = this.$createElement
        const msgArr = [
          h(
            'div',
            null,
            '虚机扩缩容参数会对微服务所在如下集群生效，请确认是否继续修改 '
          )
        ]
        this.choosedClusters.forEach((element) => {
          const str =
            '云商：' +
            element.providerName +
            '，集群：' +
            element.clusterName +
            '  '
          msgArr.push(h('span', { style: 'color: teal' }, str))
        })
        this.$msgbox({
          title: '警告',
          message: h('div', null, msgArr),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then((action) => {
          // 确认修改
          this.confirmHandle()
        })
        return
      }
      this.confirmHandle()
    },
    /**
     * @description:
     * @return {*}
     */
    confirmHandle() {
      // 组装数据
      const serviceIds = this.isEdit
        ? [this.info.serviceId]
        : this.info.serviceIds
      const scaleParams = []
      serviceIds.forEach((serviceId) => {
        const scaleParam = {
          svcId: serviceId
        }
        Object.keys(this.scaleTypes).forEach((element) => {
          let paramsObj = {}
          if (element === 'cluster') {
            // 跨集群
            paramsObj =
              this.policyCluster === 'none'
                ? {
                  policy: this.policyCluster
                }
                : {
                  policy: this.policyCluster,
                  ...this.policyClusterForm
                }
            scaleParam['cluster'] = {
              svcId: serviceId,
              scaleType: element,
              strategyName: STRATEGY_SCALE_NAME_ALL[this.policyCluster].label,
              params: JSON.stringify(paramsObj)
            }
          } else if (element === 'container') {
            // 容器
            paramsObj =
              this.policyCtn !== 'hpa'
                ? {
                  policy: this.policyCtn
                }
                : {
                  policy: this.policyCtn,
                  ...this.policyCtnHpaForm
                }
            scaleParam['container'] = {
              svcId: serviceId,
              scaleType: element,
              strategyName: STRATEGY_SCALE_NAME_ALL[this.policyCtn].label,
              params: JSON.stringify(paramsObj)
            }
          } else if (element === 'vm') {
            // 虚机
            paramsObj =
              this.policyVM === 'none'
                ? {
                  policy: this.policyVM
                }
                : {
                  policy: this.policyVM,
                  param: this.policyVMParam
                }
            scaleParam['vm'] = {
              svcId: serviceId,
              scaleType: element,
              strategyName: STRATEGY_SCALE_NAME_ALL[this.policyVM].label,
              params: JSON.stringify(paramsObj)
            }
          }
        })
        scaleParams.push(scaleParam)
      })
      // 添加
      this.confirmLoading = true
      addScaleStrategy(scaleParams)
        .then((res) => {
          this.$emit('update:show', false)
          if (this.isEdit) {
            this.$emit('edit-success', scaleParams) // 抛出事件
          } else {
            this.$emit('add-success') // 抛出事件
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    /**
     * @description: 关闭
     * @return {*}
     */
    closeClick() {
      this.$emit('update:show', false)
    },
    /**
     * @description: 取消
     * @return {*}
     */
    cancelClick() {
      this.closeClick()
      this.$emit('cancel')
    }
  }
}
</script>
<style lang="less" scoped>
@import "@/assets/css/common.less";
.scale-strategy-dialog {
  .serviceName {
    .textStyle(15px , 500, #333333);
    .text {
      .textStyle(14px , 400, #4a4a4a);
      line-height: 20px;
    }
  }
  .tabs {
    /deep/ .el-tabs__header {
      margin-top: 10px;
      margin-bottom: 20px;
    }
    /deep/ .el-tabs__item {
      height: 36px;
      line-height: 36px;
      font-weight: 500;
    }
  }
  .collapse {
    border: none;
    margin-top: 15px;
    /deep/ .el-collapse-item__header {
      border-bottom: none;
      background-color: #f3f3f3;
      padding-left: 15px;
      .textStyle(14px , 400, #696969);
      height: 40px;
    }
    /deep/ .el-collapse-item__wrap {
      background-color: #fdfdfd;
      border: 1px solid #ececec;
      border-top: none;
      .el-collapse-item__content {
        padding-bottom: 0px;
      }
    }
  }
  .scale-form {
    padding-top: 15px;
    padding-right: 10px;
    position: relative;

    .half {
      display: inline-block;
      width: calc(50% - 25px);
      &:first-child {
        margin-right: 50px;
      }
    }

    .subtitle {
      width: 70px;
      text-align: right;
      margin-right: 15px;

      &.cluster {
        width: 100px;
      }
    }

    .cooldownDelay {
      width: 130px;
    }

    .slider {
      flex: 1;
    }
  }
}
</style>
